﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace SharpHomeEngine
{
    public abstract class Request
    {
        public readonly Int64 ID;
        public readonly Controller Controller;
        public readonly StateEngine Engine;

        internal AutoResetEvent AutoResetEvent;

        internal bool Successful = false;
        internal bool Completed = false;

        public static Int64 RequestIDSource = 0;

        internal Request(Controller Controller)
        {
            this.Engine = StateEngine.Engine;
            this.Controller = Controller;
            lock (this)
            {
                ID = ++RequestIDSource;
            }
        }

        internal protected virtual void DoRequest()
        {
            throw new NotImplementedException();
        }

        public virtual void Succeed()
        {
            this.Completed = true;
            this.Successful = true;
            Finish();
        }

        public virtual void Fail()
        {
            this.Completed = true;
            this.Successful = false;
            Finish();
        }

        public virtual void Error()
        {
            this.Completed = false;
            this.Successful = false;
            Finish();
        }

        public void Finish()
        {
            Engine.RaiseRequestCompleted(this);
            Unblock();
        }

        public void Unblock()
        {
            if (AutoResetEvent != null)
            {
                AutoResetEvent.Set();
            }
        }

        public virtual void Complete(bool Completed, bool Successful)
        {
            this.Completed = Completed;
            this.Successful = Successful;
            Finish();
        }

        public void Wait(int TimeOutMilliSec)
        {
            AutoResetEvent = new AutoResetEvent(false);
            AutoResetEvent.WaitOne(TimeOutMilliSec);
        }
    }

}
